package com.atguigu.guli.service.edu.controller.api;


import com.atguigu.guli.service.base.dto.CourseDto;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.edu.entity.Course;
import com.atguigu.guli.service.edu.entity.Teacher;
import com.atguigu.guli.service.edu.entity.query.CourseSearch;
import com.atguigu.guli.service.edu.entity.vo.CourseDetailsVo;
import com.atguigu.guli.service.edu.service.CourseService;
import com.atguigu.guli.service.edu.service.TeacherService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2021-07-27
 */
@RestController
@RequestMapping("/api/edu/course")
public class ApiCourseController {
    @Autowired
    CourseService courseService;
    //3、根据课程id查询课程详情页数据

    @Autowired
    TeacherService teacherService;

    @GetMapping("getCourseById/{courseId}")
    public R getCourseByCourseId(@PathVariable String courseId){

        Course course = courseService.getById(courseId);
        Teacher teacher = teacherService.getById(course.getTeacherId());
        CourseDto courseDto = new CourseDto(course.getId(),course.getTitle(),course.getPrice(),course.getCover(),teacher.getName());
        return R.ok().data("courseDto",courseDto);
    }

    @GetMapping("getCourseDetails/{courseId}")
    public R getCoursesDetails(@PathVariable String courseId){
        CourseDetailsVo vo = courseService.getCoursesDetails(courseId);
        return R.ok().data("item" , vo);
    }
    //2、根据条件查询课程列表
    @GetMapping("list")
    public R listCourses(CourseSearch courseSearch){
        List<Course> courses = courseService.listCourses(courseSearch);
        return R.ok().data("items" , courses);
    }
    //根据讲师id查询他讲过的课程列表
    @GetMapping("getCourses/{teacherId}")
    public R getCourseByTeacherId(@PathVariable String teacherId){
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Course::getId,Course::getCover , Course::getTitle);
        queryWrapper.eq(Course::getTeacherId , teacherId);
        List<Course> courses = courseService.list(queryWrapper);
        return R.ok().data("items" , courses);
    }

    @PutMapping("/updateSales/{courseId}")
    public R updateSales(@PathVariable String courseId){
        Course course = courseService.getById(courseId);
        LambdaUpdateWrapper<Course> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Course::getBuyCount,course.getBuyCount()+1);
        courseService.update(updateWrapper);
        return R.ok();
    }
}

